package com.le.tester.book.concurrentchallenge.imgView9;

import com.le.tester.sevice.StockService;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.*;

/**
 * createTime：2025-04-17 14:19
 * description：使用Executor来实现SwingUtil
 */
public class SwingUtilities {

    private static final ExecutorService exec = Executors.newSingleThreadExecutor(new SwingThreadFactory());

    private static volatile Thread swingThread;

    private static class SwingThreadFactory implements ThreadFactory {

        public Thread newThread(Runnable r) {
            swingThread = new Thread(r);
            return swingThread;
        }
    }

    public static boolean isEventDispatchThread() {
        return Thread.currentThread() == swingThread;
    }

    public static void invokeLater(Runnable task) {
        exec.execute(task);
    }

    public static void invokeAndWait(Runnable task) throws InvocationTargetException {
        Future<?> f = exec.submit(task);
        try {
            f.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new InvocationTargetException(e);
        }
    }


}
